package com.yc.leetcode;

import java.util.Stack;

public class StackTest {
    public static void main(String[] args) {
        StackTest t = new StackTest();
        t.m1();
    }

    public void m1() {
        String s = "3[a]2[bc]";
        System.out.println(decodeString(s));

    }

    public String decodeString(String s) {
        Stack<String> stack = new Stack<>();
        StringBuilder sb = new StringBuilder();
        for(int i=s.length()-1; i>=0; i--) {
            if (s.charAt(i) == '[') {
                //字符串出栈
                String str = getStackString(sb, stack);
                //找出完整数字
                sb.setLength(0);
                while(--i>=0 && Character.isDigit(s.charAt(i))) {
                    sb.insert(0, s.charAt(i));
                }
                i++;//多减的加回来
                Integer num = Integer.parseInt(sb.toString());
                //复制出完整的字符串，并重新入栈
                copyStr(sb, stack, str, num);
            } else {
                stack.push(s.charAt(i)+"");
            }
        }
        sb.setLength(0);
        while(!stack.empty()) {
            sb.append(stack.pop());
        }

        return sb.toString();
    }

    public String getStackString(StringBuilder sb, Stack<String> stack) {
        sb.setLength(0);
        while(!stack.peek().equals("]")) {
            sb.append(stack.pop());
        }
        stack.pop();
        return sb.toString();
    }


    public void copyStr(StringBuilder sb, Stack<String> stack, String str, int num) {
        sb.setLength(0);
        for (int i=0; i<num; i++) {
            sb.append(str);
        }
        stack.push(sb.toString());
    }
}
